import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Simple chat server application designed to demonstrate basic Java networking.
 * Displays IP address for client to request connection.  Listens for connection
 * on specified port number.  Establishes connection with client.  Prompts user
 * for chat message, sends to client, waits for client response.  Loops until
 * client responds with "bye."
 * 
 * @author charlieg
 * @author <a href="mailto:charlieg@cis.udel.edu">charlieg@cis.udel.edu</a>
 * @author <a href="http://www.cis.udel.edu/~charlieg">www.cis.udel.edu/~charlieg</a>
 * @version 1.0, &nbsp; 04 Nov 2009
 *
 */
public class ChatServer {
    public static void main(String[] args) throws IOException {
    	
    	int portNumber = 9876;  // each team should choose a unique number
    	
    	ServerSocket serverSocket = null;
    	Socket clientSocket = null;
    	PrintWriter socketOut = null;
    	BufferedReader socketIn = null, consoleIn = null;
        String toClient = "", fromClient = "";
        
        // display server IP address for client to input
        System.out.println("Server IP address: " + InetAddress.getLocalHost().getHostAddress());
        System.out.println("(client must enter this IP address to connect)\n");
    	
    	// listen for inbound connection
        try {
            serverSocket = new ServerSocket(portNumber);
            System.out.print("Listing for inbound connection on port " + portNumber + "... ");
        } catch (IOException e) {
            System.err.println("Could not listen on port: " + portNumber + ". error: " + e);
            System.exit(1);
        }

        // accept connection request
        try {
            clientSocket = serverSocket.accept();
            System.out.println("Connection established!");
        } catch (IOException e) {
            System.err.println("Accept failed. error: " + e);
            System.exit(1);
        }

        // instantiate I/O objects
        socketOut = new PrintWriter(clientSocket.getOutputStream(), true);
        socketIn = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        consoleIn = new BufferedReader(new InputStreamReader(System.in));
        
        // loop conversation until "bye" is received
        while (!fromClient.equalsIgnoreCase("bye")) {
	        System.out.print("you: ");
	        toClient = consoleIn.readLine();
	        socketOut.println(toClient);

	        fromClient = socketIn.readLine();
	        System.out.println("them: " + fromClient);
        }
        
        // close I/O connections
        socketOut.close();
        socketIn.close();
        consoleIn.close();
        clientSocket.close();
        serverSocket.close();
    }
}